<?php

/**
 * yaf 框架报错类调用
 *  默认错误会调用这个Controller 中 ErrorAction
 */
class ErrorController extends Yaf_Controller_Abstract
{

    private $_config;

    public function init()
    {
        Yaf_Dispatcher::getInstance()->disableView();
        $this->_config  = Yaf_Application::app()->getConfig();
    }

    /**
     * [yaf错误处理]
     * @param Throwable $exception [description]
     * @return [type]               [description]
     */
    public function errorAction(\Throwable $exception)
    {
        $module = $this->request->getModuleName();
        switch ($exception->getCode()) {
            case YAF_ERR_AUTOLOAD_FAILED:
            case YAF_ERR_NOTFOUND_MODULE:
            case YAF_ERR_NOTFOUND_CONTROLLER:
            case YAF_ERR_NOTFOUND_ACTION:
            case YAF_ERR_NOTFOUND_VIEW:
                $result = ($module == 'Index') ? [
                    'code' => $exception->getCode(),
                    'msg' => $exception->getMessage(),
                ] : [
                    'ret' => $exception->getCode(),
                    'msg' => $exception->getMessage(),
                ];
                break;
            default:
                Log::out($exception->getMessage() . ' IN FILE ' . $exception->getFile() . ' ON LINE ' . $exception->getLine(), 'error');
                $result = ($module == 'Index') ? [
                    'code' => $exception->getCode(),
                    'msg' => $exception->getMessage(),
                ] : [
                    'ret' => $exception->getCode(),
                    'msg' => $exception->getMessage(),
                ];
        }
        if ($this->_config->application->debug) {
            #debug模式，添加错误代码、文件、及行号
            $result['data'] = [
                'code' => $exception->getCode(),
                'file' => $exception->getFile(),
                'line' => $exception->getLine(),
            ];
            if (NULL !== $exception->getPrevious()) {
                $result['data']['file'] = $exception->getPrevious()->getFile();
                $result['data']['line'] = $exception->getPrevious()->getLine();
                $result['data']['msg']  = $exception->getPrevious()->getMessage();
            }
        }
        if (php_sapi_name() === 'cli' || Yaf_Dispatcher::getInstance()->getRequest()->isPost()) {
            json($result);
        } else {
            $this->_view->assign('dataset', $result);
            if (in_array($exception->getCode(), [516, 404])) {
                $this->_view->display('error/404.html');
            } else {
                $this->_view->display('error/error.html');
            }
        }
    }

}
